//
//  BDUtil.m
//  ProjectForBD
//
//  Created by Jaesun on 17/2/15.
//  Copyright © 2017年 S.J. All rights reserved.
//

#import "BDUtil.h"

@implementation BDUtil

#pragma mark- APP 相关信息
/**
 *  获取版本号
 */
+(NSString*)getVersion:(BOOL)hiddinBuild{
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    if(hiddinBuild){
        return [NSString stringWithFormat:@"%@",app_Version];
    }
    else{
        NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
        
        return [NSString stringWithFormat:@"%@（%@）",app_Version,app_build];
    }
}

/**
 *  获取APP名称
 */
+(NSString*)getAppName{
    
    NSString *app_Name =  NSPublicLocalizedString(@"CFBundleDisplayNames", @"");
    
    return app_Name;
}



/**
 检查APP新版本首次运行
 
 @return 是否为首次运行APP
 */
+ (BOOL)isAppFirstRunInCurVersion {
    
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *lastRunKey = [defaults objectForKey:@"last_run_version_key"];
    
    if (!lastRunKey) {
        [defaults setObject:currentVersion forKey:@"last_run_version_key"];
        return YES;
        // App is being run for first time
        //上次运行版本为空，说明程序第一次运行
    }
    else if (![lastRunKey isEqualToString:currentVersion]) {
        [defaults setObject:currentVersion forKey:@"last_run_version_key"];
        return YES;
        // App has been updated since last run
        //有版本号，但是和当前版本号不同，说明程序已经更新了版本
    }
    return NO;
}

#pragma mark 设备相关
//获取设备型号
+(NSString*)getDeviceModel{
    
    int mib[2];
    size_t len;
    char *machine;
    
    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    
    if ([platform isEqualToString:@"iPhone1,1"])
    {platform=@"iPhone 2G (A1203)";
    }
    else if ([platform isEqualToString:@"iPhone1,2"]) {platform= @"iPhone 3G (A1241/A1324)";}
    else if ([platform isEqualToString:@"iPhone2,1"]) {platform= @"iPhone 3GS (A1303/A1325)";}
    else if ([platform isEqualToString:@"iPhone3,1"]) {platform= @"iPhone 4 (A1332)";}
    else if ([platform isEqualToString:@"iPhone3,2"]) {platform= @"iPhone 4 (A1332)";}
    else if ([platform isEqualToString:@"iPhone3,3"]) {platform= @"iPhone 4 (A1349)";}
    else if ([platform isEqualToString:@"iPhone4,1"]) {platform= @"iPhone 4S (A1387/A1431)";}
    else if ([platform isEqualToString:@"iPhone5,1"]) {platform= @"iPhone 5 (A1428)";}
    else if ([platform isEqualToString:@"iPhone5,2"]) {platform= @"iPhone 5 (A1429/A1442)";}
    else if ([platform isEqualToString:@"iPhone5,3"]) {platform= @"iPhone 5c (A1456/A1532)";}
    else if ([platform isEqualToString:@"iPhone5,4"]) {platform= @"iPhone 5c (A1507/A1516/A1526/A1529)";}
    else if ([platform isEqualToString:@"iPhone6,1"]) {platform= @"iPhone 5s (A1453/A1533)";}
    else if ([platform isEqualToString:@"iPhone6,2"]) {platform= @"iPhone 5s (A1457/A1518/A1528/A1530)";}
    else if ([platform isEqualToString:@"iPhone7,1"]) {platform= @"iPhone 6 Plus (A1522/A1524)";}
    else if ([platform isEqualToString:@"iPhone7,2"]) {platform= @"iPhone 6 (A1549/A1586)";}
    
    else if ([platform isEqualToString:@"iPod1,1"])   {platform= @"iPod Touch 1G (A1213)";}
    else if ([platform isEqualToString:@"iPod2,1"])   {platform= @"iPod Touch 2G (A1288)";}
    else if ([platform isEqualToString:@"iPod3,1"])   {platform= @"iPod Touch 3G (A1318)";}
    else if ([platform isEqualToString:@"iPod4,1"])   {platform= @"iPod Touch 4G (A1367)";}
    else if ([platform isEqualToString:@"iPod5,1"])   {platform= @"iPod Touch 5G (A1421/A1509)";}
    
    else if ([platform isEqualToString:@"iPad1,1"])   {platform= @"iPad 1G (A1219/A1337)";}
    
    else if ([platform isEqualToString:@"iPad2,1"])   {platform= @"iPad 2 (A1395)";}
    else if ([platform isEqualToString:@"iPad2,2"])   {platform= @"iPad 2 (A1396)";}
    else if ([platform isEqualToString:@"iPad2,3"])   {platform= @"iPad 2 (A1397)";}
    else if ([platform isEqualToString:@"iPad2,4"])   {platform= @"iPad 2 (A1395+New Chip)";}
    else if ([platform isEqualToString:@"iPad2,5"])   {platform= @"iPad Mini 1G (A1432)";}
    else if ([platform isEqualToString:@"iPad2,6"])   {platform= @"iPad Mini 1G (A1454)";}
    else  if ([platform isEqualToString:@"iPad2,7"])   {platform= @"iPad Mini 1G (A1455)";}
    else if ([platform isEqualToString:@"iPad3,1"])   {platform= @"iPad 3 (A1416)";}
    else if ([platform isEqualToString:@"iPad3,2"])   {platform= @"iPad 3 (A1403)";}
    else if ([platform isEqualToString:@"iPad3,3"])   {platform= @"iPad 3 (A1430)";}
    else  if ([platform isEqualToString:@"iPad3,4"])   {platform= @"iPad 4 (A1458)";}
    else  if ([platform isEqualToString:@"iPad3,5"])   {platform= @"iPad 4 (A1459)";}
    else if ([platform isEqualToString:@"iPad3,6"])   {platform= @"iPad 4 (A1460)";}
    
    else  if ([platform isEqualToString:@"iPad4,1"])   {platform= @"iPad Air (A1474)";}
    else  if ([platform isEqualToString:@"iPad4,2"])   {platform= @"iPad Air (A1475)";}
    else  if ([platform isEqualToString:@"iPad4,3"])   {platform= @"iPad Air (A1476)";}
    else  if ([platform isEqualToString:@"iPad4,4"])   {platform= @"iPad Mini 2G (A1489)";}
    else  if ([platform isEqualToString:@"iPad4,5"])   {platform= @"iPad Mini 2G (A1490)";}
    else  if ([platform isEqualToString:@"iPad4,6"])   {platform= @"iPad Mini 2G (A1491)";}
    
    else  if ([platform isEqualToString:@"i386"])      {platform= @"iPhone Simulator";}
    else  if ([platform isEqualToString:@"x86_64"])    {platform= @"iPhone Simulator";}
    platform=[BDUtil clearSpace:platform isends:NO];
    platform=[BDUtil stringReplace:platform replace:@"(" target:@"["];
    platform=[BDUtil stringReplace:platform replace:@")" target:@"]"];
    return platform;
}


#pragma mark- 服务器地址相关

/**
 *  获取当前APP请求地址
 */
+ (NSString*)getUsedHost{
    
    NSString *usedHost;
    
    BOOL UserSelected = [[NSUserDefaults standardUserDefaults] boolForKey:IS_USER_SElELECTED];
    
    if (!UserSelected) {
        usedHost = [self getRecommendHost];
    }
    else {
        usedHost = [self getUserHost];
    }
    
    return usedHost;
}

/**
 获取用户选择的自己添加的服务器地址
 
 @return 用户返回的服务器地址
 */
+ (NSString *)getUserHost {
    
    NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    NSString *userServer = [userDefaults objectForKey:USER_SERVER];
    
    if ([BDUtil isEmptyString:userServer]) {
        userServer = HOST;
    }
    return userServer;
}

/**
 *   当用户选择自己添加的服务器地址时调用
 *   @param host  eg: http://www.hid.s:8080
 */
+(BOOL)setUserHost:(NSString *)host {
    
    [[NSUserDefaults standardUserDefaults] setObject:host forKey:USER_SERVER];
    
    if (!([host hasPrefix:@"https://"]||[host hasPrefix:@"http://"])) {
        return NO;
    }
    
    // 用户选择了服务器地址
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:IS_USER_SElELECTED];
    return YES;
}

/**
 *  获取系统推荐服务器地址
 */
+ (NSString*)getRecommendHost{
    
    NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    
    [userDefaults setObject:@"" forKey:RECOMMEND_SERVER];
    
    NSString *host = [userDefaults objectForKey:RECOMMEND_SERVER];
    
    if ([BDUtil isEmptyString:host]) {
        host = HOST;
        [userDefaults setObject:host forKey:RECOMMEND_SERVER];
    }
    return host;
}

/**
 *  获取请求地址列表
 */
+ (NSMutableArray *)getHostList {
    
    NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    NSMutableArray *hostArray= [NSMutableArray arrayWithArray:[userDefaults objectForKey:ADD_SERVERS]];
    return hostArray;
}

/**
 *  添加请求地址: 如果地址不合法不添加;如果地址在推荐栏中,不添加; 如果是已经存在的地址添加
 *
 *  @param host eg: http://www.hid.s:8080
 *
 *  @return 操作结果
 */
+ (BOOL)addHost:(NSString*)host {
    
    NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    
    if ([host isEqualToString:[userDefaults objectForKey:RECOMMEND_SERVER]]) {
        // [[BDHUD sharedManager] showWords:@"系统推荐服务器地址"];
        return NO;
    }
    
    NSMutableArray *hostArray=[NSMutableArray arrayWithArray:[userDefaults objectForKey:ADD_SERVERS]];
    for (NSString *existHost in hostArray) {
        if ([host isEqualToString:existHost]) {
            // [[BDHUD sharedManager] showWords:@"已存在服务器地址"];
            return NO;
        }
    }
    NSInteger beforeAdd = hostArray.count;
    [hostArray addObject:host];
    [userDefaults setObject:hostArray forKey:ADD_SERVERS];
    NSInteger afterAdd = hostArray.count;
    if (beforeAdd == afterAdd) {
        //      [[BDHUD sharedManager] showWords:@"添加失败"];
        return NO;
    }
    return YES;
}

/**
 @param host 为从特定服务器中的TXT文本中获取的服务器地址
 */
+ (void)setRecommendHost:(NSString *)host {
    
    NSString *severHost = [[NSUserDefaults standardUserDefaults] objectForKey:RECOMMEND_SERVER];
    
    if ([self isAppFirstRunInCurVersion]) {
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:RECOMMEND_SERVER];
    }
    if (![BDUtil isEmptyString:host
          ] && [host hasPrefix:@"http://"]) {
        [[NSUserDefaults standardUserDefaults] setObject:host forKey:RECOMMEND_SERVER];
    }
    else {
        if ([BDUtil isEmptyString:severHost]){
            [[NSUserDefaults standardUserDefaults] setObject:HOST forKey:RECOMMEND_SERVER];
        }
    }
}


/**
 *  删除服务器地址
 */
+ (BOOL)deleteHostAtIndex:(NSInteger)index {
    
    NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
    NSMutableArray *hostarray=[NSMutableArray arrayWithArray:[userDefaults objectForKey:ADD_SERVERS]];
    
    NSInteger deleteBefore = hostarray.count;
    [hostarray removeObjectAtIndex:index];
    [userDefaults setObject:hostarray forKey:ADD_SERVERS];
    NSInteger deleteAfter = hostarray.count;
    if (deleteBefore == deleteAfter) {
        return NO;
    }
    return YES;
    
}


//#pragma mark- 用户账号相关
///*用户是否登录*/
//+ (BOOL)isLogin {
//    if([self getAccountInfo].key.length < 1||[[self getAccountInfo].key isEqualToString:@"null"]){
//        return NO;
//    }
//    else {
//        return YES;
//    }
//}

///**
// *  注销 或者修改密码
// */
//+ (void)removeAccount {
//
//    [[NSUserDefaults standardUserDefaults] removeObjectForKey:USERINFO];
//    [[NSUserDefaults standardUserDefaults] synchronize];
//    [THUserInfoModel writeDataArray:[[[NSArray alloc] init] mutableCopy]   ModelKey:USERINFO];
//}

/**
 *  保存账号密码(仅仅是账号密码)
 */
+ (void)saveAccountInfo:(NSDictionary*)accountDict {
    
    //非空
    if(accountDict){
        /**
         *  注 : 因后台会返回<null>字符串  如果是null则保存空
         */
        NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
        [userdefaults setObject:accountDict forKey:USERACCOUT];
        [userdefaults synchronize];
    }
}

///**
// *  保存账户信息 模型信息
// */
//+ (void)saveAccountModel:(THUserInfoModel*)userModel {
//
//    [THUserInfoModel writeDataArray:[@[userModel] mutableCopy] ModelKey:USERINFO];
//}

///**
// *  获取用户账号信息 模型信息
// */
//+ (THUserInfoModel*)getAccountInfo {
//
//    NSArray *a=[THUserInfoModel readDataArrayByModelKey:USERINFO];
//    THUserInfoModel * accountInfo=[[THUserInfoModel alloc] init];
//
//    if(a.count>0){
//        accountInfo= (THUserInfoModel*) a[0];
//    }
//    return accountInfo;
//}

///**
// *  获取用户口令
// */
//+ (NSString*)getKey {
//
//    if ([self getAccountInfo].key.length<1) {
//        return @"admin";
//    }
//    else{
//        return [NSString stringWithFormat:@"%@",[self getAccountInfo].key];
//    }
//}

/**
 *  获取账号密码
 */
+ (NSDictionary*)getKeepAccout {
    
    return [[NSUserDefaults standardUserDefaults] objectForKey:USERACCOUT];
}

#pragma mark- 颜色相关
//16进制颜色(html颜色值)字符串转为UIColor
+ (UIColor *) hexStringToColor: (NSString *) stringToConvert  alpha:(CGFloat)alpha{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6)
        return [UIColor blackColor];
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor blackColor];
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    if(alpha==0){
        alpha=0.01;
    }
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f)                         alpha:alpha];
}

/**
 * RGB色值 0-255
 */
+ (UIColor*)rgbColor:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha {
    return [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha] ;
}


#pragma mark- JSON

/**
 *标准化json
 */
+(NSDictionary*)formatJSON:(NSDictionary*)responseObject{
    
    NSString *json = [BDUtil dictionaryToJson:[NSMutableDictionary dictionaryWithDictionary:responseObject]];
    
    json=[json stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
    json=[json stringByReplacingOccurrencesOfString:@"'" withString:@"‘"];
    json=[json stringByReplacingOccurrencesOfString:@"?" withString:@" "];
    json=[json stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    json=[json stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    json=[json stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    json=[json stringByReplacingOccurrencesOfString:@"\v" withString:@""];
    json=[json stringByReplacingOccurrencesOfString:@"\f" withString:@""];
    json=[json stringByReplacingOccurrencesOfString:@"\b" withString:@""];
    json=[json stringByReplacingOccurrencesOfString:@"\a" withString:@""];
    json=[json stringByReplacingOccurrencesOfString:@"\e" withString:@""];
    json=[json stringByReplacingOccurrencesOfString:@"':," withString:@"':'',"];
    json=[json stringByReplacingOccurrencesOfString:@"':}" withString:@"':''}"];
    json=[json stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
    json =[json stringByReplacingOccurrencesOfString:@"(null)" withString:@""];
    json =[json stringByReplacingOccurrencesOfString:@"<null>" withString:@""];
    json =[json stringByReplacingOccurrencesOfString:@"null" withString:@"\"\""];
    
    return [BDUtil  dictionaryWithJsonString:json];
}

/**
 *字典转JSON
 */
+ (NSString*)dictionaryToJson:(NSMutableDictionary *)dic;
{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}


/**
 JSON字符串转化为字典

 @param jsonString JSON字符串
 @return 字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    jsonString = [self removeUnescapedCharacter:jsonString];
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err=nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        return nil;
    }
    return dic;
}

+ (NSString *)removeUnescapedCharacter:(NSString *)inputStr{    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
    
    //获取那些特殊字符
    NSRange range = [inputStr rangeOfCharacterFromSet:controlChars];
    //寻找字符串中有没有这些特殊字符
    if (range.location != NSNotFound)    {
        NSMutableString *mutable = [NSMutableString stringWithString:inputStr];
        while (range.location != NSNotFound)
        {
            [mutable deleteCharactersInRange:range];
            //去掉这些特殊字符
            range = [mutable rangeOfCharacterFromSet:controlChars];        }
        return mutable;
    }
    return inputStr;
}   


#pragma mark 数据加密、解密
/**
 *  字典DES加密成字符串
 *
 *  @param sourceDict 源字典
 *  @param bencrypt 是否加密
 *  @return 加密结果
 */
+(NSString*)encryption:(NSMutableDictionary*)sourceDict  encrypt:(BOOL)bencrypt{
    NSString *resultString=@"";
    if(!sourceDict){
        return resultString;
    }
    NSString *jsonString = [self dictionaryToJson:sourceDict];
    resultString=[jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    if(bencrypt){
        //加密
        
        resultString= __DesEncodeString(resultString);
        
    }
    return resultString;
}
/**
 *  加密字符串DES解密成字典
 *
 *  @param sourceString 源字符串
 *  @param bencrypt 是否加密
 *  @return 解密结果
 */
+(NSMutableDictionary*)decryption:(NSString*)sourceString  encrypt:(BOOL)bencrypt{
    
    NSMutableDictionary *resultDict=[[NSMutableDictionary alloc] initWithCapacity:0];
    
    if(!sourceString){
        return resultDict;
    }
    if(bencrypt){
        //字符串解密
        NSString * jsonString = __DesDecodeString(sourceString);
        jsonString=[BDUtil stringReplace:jsonString replace:@"+" target:@" "];
        jsonString = [jsonString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        NSLog(@"解码后的请求结果是：%@",jsonString);
        
        resultDict = [[self dictionaryWithJsonString:jsonString] mutableCopy];
    }
    else{
        resultDict = [[self dictionaryWithJsonString:sourceString] mutableCopy];
    }
    return resultDict;
}

#pragma mark- 日期相关
+ (NSString *)dateString:(NSString *)inputDateStr fromDateFormatter:(NSString *)inputDateFormatter toDateFormatter:(NSString *)outputDateFormatter {
    
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:inputDateFormatter];
    NSDate *theDate = [inputFormatter dateFromString:inputDateStr];
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:outputDateFormatter];
    NSString *outputDateStr = [outputFormatter stringFromDate:theDate];
    
    return outputDateStr;
}

+ (NSDate *)dateWithString:(NSString *)dateStr formatter:(NSString *)formatter {
    
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setDateFormat:formatter];
    NSDate *theDate = [inputFormatter dateFromString:dateStr];
    
    return theDate;
}

+ (NSString *)customTimestampWithDate:(NSDate *)theDate {
    
    int minuteInt = 60;
    int hourInt   = 60 * 60;
    int dayInt    = 60 * 60 * 24;
    int weekInt   = 60 * 60 * 24 * 7;
    
    NSTimeInterval timeInterval = [theDate timeIntervalSinceNow];
    int timeIntervalFab = (int)fabs(timeInterval);
    
    if (timeIntervalFab < minuteInt) { // 1分钟内
        return @"Just now";
    }
    else if (minuteInt <= timeIntervalFab && timeIntervalFab < minuteInt * 2) { // 一分钟到2分钟
        return @"1 minute ago";
    }
    else if (minuteInt * 2 <= timeIntervalFab && timeIntervalFab < hourInt) { // 2分钟到一个小时
        
        return [NSString stringWithFormat:@"%d minutes ago",timeIntervalFab / minuteInt];
    }
    else if (hourInt <= timeIntervalFab && timeIntervalFab < hourInt * 2) {
        return  @"1 hour ago";
    }
    else if (hourInt * 2 <= timeIntervalFab && timeIntervalFab < dayInt) {
        return [NSString stringWithFormat:@"%d hours ago",timeIntervalFab / hourInt];
    }
    else if (dayInt <= timeIntervalFab && timeIntervalFab < dayInt * 2) { // 一天到两天,即昨天
        return @"Yesterday";
    }
    else if (dayInt * 2 < timeIntervalFab && timeIntervalFab < weekInt) {
        return [NSString stringWithFormat:@"%d days ago",timeIntervalFab / dayInt];
    }
    else if (weekInt <= timeIntervalFab && timeIntervalFab < weekInt * 2) {
        return @"a week ago";
    }
    else if (weekInt * 2 <= timeIntervalFab && timeIntervalFab < weekInt * 5) {
        return [NSString stringWithFormat:@"%d weeks ago",timeIntervalFab / weekInt];
    }
    else {
        NSDateFormatter *shortDateFormatter = [[NSDateFormatter alloc] init];
        [shortDateFormatter setDateFormat:@"yyyy-MM-dd"];
        return [shortDateFormatter stringFromDate:theDate];
    }
}

+ (NSString *)stringFromDate:(NSDate *)date withFormatter:(NSString *)dateFormatter {
    NSString *dateString;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:dateFormatter];
    if (dateFormatter.length == 0) {
        [formatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
    }
    dateString = [formatter stringFromDate:date];
    return dateString;
}
/**
 *标准时间指定格式时间转时间戳
 */
+(NSString*)dateToTimestamp{
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    
    NSInteger interval = [zone secondsFromGMTForDate:datenow];
    
    NSDate *localeDate = [datenow  dateByAddingTimeInterval:interval];
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld",(long)[localeDate timeIntervalSince1970]];
    
    return timeSp;
}
#pragma mark- Frame相关

/**
 计算字符串高度
 
 @param string 字符串
 @param fontSize 字符size
 @return 字符串高度
 */
+ (CGFloat)heightForString:(NSString *)string width:(CGFloat)width fontSize:(CGFloat)fontSize {
    
    CGRect rect = [string boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:CustomFont(fontSize)} context:nil];
    return rect.size.height;
}

/**
 计算字符串长度
 
 @param string 字符串
 @param fontSize 字符size
 @return 字符串长度
 */
+ (CGFloat)widthForString:(NSString *)string height:(CGFloat)height fontSize:(CGFloat)fontSize {
    
    NSDictionary *attributeDic = @{NSFontAttributeName:[UIFont systemFontOfSize: fontSize],NSForegroundColorAttributeName:[UIColor whiteColor]};
    
    CGRect rect = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, fontSize * 2) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:attributeDic context:nil];
    return rect.size.width;
    
}

/**
 *返回范围 文本  最大范围 字号
 */
+ (CGSize)sizeWithString:(NSString *)string CGsize:(CGSize)size font:(UIFont *)font
{
    //限制最大的宽度和高度
    CGRect rect = [string boundingRectWithSize:size
                                       options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading  |NSStringDrawingUsesLineFragmentOrigin//采用换行模式
                                    attributes:@{NSFontAttributeName: font}//传人的字体字典
                                       context:nil];
    
    return rect.size;
}

/**
 *文件是否纯在
 @param filePath 文件路劲
 */
+ (BOOL)isExsitfile:(NSString *)filePath{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if(![fileManager fileExistsAtPath:filePath]) //如果不存在
        
    {
        return NO;
        
    }
    else{
        return YES;
    }
}

#pragma mark- Others
/**
 *去掉导航黑线
 */
+ (UIImage *)clearBlackNavigation:(UIColor *)color{
    
    CGRect rect = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,1);
    
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context,
                                   
                                   color.CGColor);
    
    
    CGContextFillRect(context, rect);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    return img;
}

/**
 *  数据深拷贝 相当于深拷贝一份data。这样才不会改变data本身的值
 *
 *  @param data 数据
 *
 *  @return 放回结果
 */
+ (id)deepCopy:(id)data{
    // 相当于深拷贝一份data。这样才不会改变data本身的值
    return [NSKeyedUnarchiver unarchiveObjectWithData:[NSKeyedArchiver archivedDataWithRootObject:data]];
}

+ (BOOL)isEmptyString:(NSString*)string {
    
    if (!string) {
        return YES;
    } else if ([string isEqualToString:@""]) {
        return YES;
    } else if ([string isEqualToString:@"(null)"]) {
        return YES;
    } else if ([string isEqualToString:@"\"null\""]) {
        return YES;
    } else if ([string isEqualToString:@"null"]) {
        return YES;
    }
    else {
        return NO;
    }
}

/**
 *去掉空格 isends 是否仅去掉首位两端 default NO
 */
+ (NSString*)clearSpace:(NSString *)str isends:(BOOL)is {
    if(is){
        return  [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
    else
    {
        return   [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
}

/**
 *字符串替换
 @ param sourceString 源字符串
 * @param replaceString 需要替换的源字符串
 * @param targetString  替换成的字符串
 */
+ (NSString*)stringReplace:(NSString*)sourceString replace:(NSString*)replaceString target:(NSString*)targetString {
    
    if([sourceString rangeOfString:replaceString].location !=NSNotFound){
        return [sourceString stringByReplacingOccurrencesOfString:replaceString withString:targetString];
    }
    return sourceString;
    
}

/**
 *字符串忽略大小写比较等值
 */
+ (BOOL)compareString:(NSString*)str1 compareString2:(NSString*)str2 {
    if([[NSString stringWithFormat:@"%@",str1] compare:[NSString stringWithFormat:@"%@",str2] options:NSCaseInsensitiveSearch]== NSOrderedSame){
        return YES;
    }
    return NO;
}


/**
 *str1字符串是否包含str2
 */
+(BOOL)compareString:(NSString*)str1 containCompareString2:(NSString*)str2 {
    if([str1 rangeOfString:str2].location !=NSNotFound)
    {
        return YES;
    }
    
    return NO;
}

/**
 *string 全部小写 lower yes
 */
+ (NSString*)compareLowercaseString:(NSString*)str1 isLower:(BOOL)lower {
    if(lower) {
        return  [str1 lowercaseString];
    }
    else{
        return  [str1 uppercaseString];
    }
    
}

+ (void)showAlterwithMessage:(NSString *)str inVC:(UIViewController *)vc
{
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"" message:str preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:[THMangerTool language:@"HUD.gotit"] style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertC addAction:action];
    [vc presentViewController:alertC animated:YES completion:nil];
    
}

//判断是否有值
+(BOOL)DataIsNuLL:(NSString *)string{
    if(string.length>0){
        return NO;
    }
    return YES;
}

/**
 *  数据字典转化成数据模型
 *
 *  @param dic   待转化字典
 *  @param model 目标模型
 *
 *  @return 转化结果
 */
//+(id)dictionarytoModel:(NSDictionary*)dic targetModel:(NSString*)model{
//    if(!dic){
//        return nil;
//    }
//    id myObj =  [(BaseModel*)[NSClassFromString(model) alloc] initContentWithDic:dic];
//    return myObj;
//}



+ (NSString *)html5URLWithInterfaceStr:(NSString *)interfaceStr parametersDic:(NSDictionary *)parametersDic {
    

    if(![BDUtil isLogin]){
        [BDUtil removeAccount];
    }
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithCapacity:0];
    
    if (parametersDic) {
        
        [parameters addEntriesFromDictionary:parametersDic];
        
    }
    
    [parameters setValue:[[UIDevice currentDevice] model] forKey:@"phoneModel"];
    [parameters setValue:[NSString stringWithFormat:@"%@",[BDUtil getVersion:YES]] forKey:@"appVersion"];
    [parameters setValue:@"ios" forKey:@"phoneType"];
    [parameters setObject:@"zh" forKey:@"language"];

    if([BDUtil isLogin]){
        [parameters setValue:[NSString stringWithFormat:@"%@",[BDUtil getKey]] forKey:@"key"];
    }
    
    
    //加密请求字符串
    NSString *requsetJson = [BDUtil encryption:parameters encrypt:YES];
    
//    parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys:requsetJson,@"request",nil];
    
    
    //不走缓存的
    NSString *httpUrl = [[BDUtil getUsedHost] stringByAppendingString:interfaceStr];
    NSString *html5Str = [NSString stringWithFormat:@"%@?msg=%@",httpUrl,requsetJson];
    NSLog(@"html5Str: %@",html5Str);
    return html5Str;
}

////是否是AppStore测试账号
//+(BOOL)isAppStoreTestAccount {
//    
//    NSDictionary *accountdict = [BDUtil getKeepAccout];
//    if ([accountdict[@"username"] isEqualToString:APPSTOREACCOUNT]) {
//        //应用商店测试账号
//        return YES;
//    }else{
//        return NO;
//    }
//    
//}

@end
